package cn.leonis.leetcode;

/**
 * @author Tobi
 * @time 2021-07-10 2:01 PM
 * 猜数字游戏，最经典的二分查找题
 */
public class GuessGameSolution {

    private static final Integer generateNumber = 63;

    public static void main(String[] args) {
        GuessGameSolution solution = new GuessGameSolution();
        System.out.println(solution.guessNumber(100));
    }

    public int guessNumber(int n) {
        int left = 1, right = n;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (guess(mid) == 0) {
                return mid;
            }else if (guess(mid) == 1) {
                left = mid + 1;
            }else {
                right = mid - 1;
            }
        }

        return right;
    }

    public int guess(int num) {
        if (num < generateNumber) {
            return 1;
        }else if (num > generateNumber) {
            return -1;
        }else {
            return 0;
        }
    }
}
